package com.gqh.weather.service;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gqh.weather.domain.dto.AccountCreateRequest;
import com.gqh.weather.domain.dto.LoginRequest;
import com.gqh.weather.domain.dto.LoginResponse;
import com.gqh.weather.domain.dto.MyPage;
import com.gqh.weather.domain.dto.PageRequest;
import com.gqh.weather.domain.entity.Account;
import com.gqh.weather.domain.entity.City;
import com.gqh.weather.domain.enums.RoleEnum;
import com.gqh.weather.exception.BusinessException;
import com.gqh.weather.exception.Result;
import com.gqh.weather.exception.ResultEnum;
import com.gqh.weather.mapper.AccountMapper;
import com.gqh.weather.mapper.CityMapper;

import cn.dev33.satoken.stp.StpUtil;

import com.gqh.weather.auth.UserContext;
import com.gqh.weather.auth.UserInfo;
import com.gqh.weather.util.PasswordUtil;
import com.gqh.weather.util.PinyinUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 账号管理服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AccountService extends ServiceImpl<AccountMapper, Account> {

    private final CityMapper cityMapper;

    /**
     * 用户登录
     *
     * @param request 登录请求
     * @return 登录结果
     */
    public Result<LoginResponse> login(LoginRequest request) {
        try {
            // 查询账号
            LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Account::getAccount, request.getAccount())
                    .eq(Account::getIsDeleted, 0);

            Account account = getOne(wrapper);
            if (account == null) {
                return Result.error("账号不存在");
            }

            // 检查账号状态
            if (account.getIfEnable() == 1) {
                return Result.error("账号已被禁用");
            }

            // 检查账号状态
            if (account.getRole() == RoleEnum.SCHOOL_ACCOUNT.getValue()) {
                return Result.error("学校账号暂不允许登录");
            }

            // 验证密码
             if (!PasswordUtil.matches(request.getPassword(), account.getPassword())) {
                 return Result.error("账号或密码错误");
             }

            // 执行Sa-Token登录
            StpUtil.login(account.getId());
            
            // 创建用户信息并存储到Session
            UserInfo userInfo = new UserInfo();
            userInfo.setUid(account.getId());
            userInfo.setUsername(account.getUsername());
            userInfo.setAccount(account.getAccount());
            userInfo.setRole(account.getRole());
            userInfo.setType(account.getType());
            userInfo.setCitycode(account.getCitycode());
            
            // 存储用户信息到Sa-Token Session
            StpUtil.getSession().set("userInfo", userInfo);

            // 构建登录响应
            LoginResponse response = new LoginResponse();
            response.setAccess_token(StpUtil.getTokenValue());
            response.setRefresh_token(""); // 暂时保留字段，返回空字符串

            return Result.success(response);

        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败");
        }
    }

    /**
     * 创建账号
     *
     * @param request 创建请求
     * @return 创建结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> createAccount(AccountCreateRequest request) {
        try {
            // 业务验证
            validateCreateRequest(request);

            // 构建Account对象
            Account account = new Account();
            BeanUtils.copyProperties(request, account);

            account.setPassword(PasswordUtil.encode(account.getPassword()));

            UserInfo userInfo = UserContext.getUserInfo();
            if (!userInfo.isAdmin()) {
                return Result.error("权限错误");
            }

            if (!userInfo.isSuperAdmin()) {
                return Result.error("权限错误");
            }

            if (!StringUtils.hasLength(userInfo.getCitycode())) {
                return Result.error("城市码参数为空");
            }

            // TO-DO: 校验citycode
            City city = cityMapper.selectByCode(request.getCitycode());
            if (city == null) {
                return Result.error("城市码参数不正确");
            }

            account.setType(1);
            account.setAccount(PinyinUtil.getPinYin(city.getName()));
            account.setRole(city.levelToRole());
            account.setPid(userInfo.getUid());

            if (baseMapper.cityExists(account.getAccount(), account.getCitycode())) {
                return Result.error("地区账号已存在");
            }

            // 保存账号
            boolean success = save(account);
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("创建账号失败");
            }

        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建账号失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 更新账号信息
     *
     * @param account 账号对象
     * @return 更新结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateAccount(Account account) {
        try {
            if (account.getId() == null) {
                return Result.error("账号ID不能为空");
            }

            // 检查账号是否存在
            Account existAccount = getById(account.getId());
            if (existAccount == null || existAccount.getIsDeleted() == 1) {
                return Result.error("账号不存在");
            }

            // 如果修改了手机号，检查新手机号是否已被其他账号使用
            if (StringUtils.hasText(account.getMobile()) &&
                    !account.getMobile().equals(existAccount.getMobile())) {
                if (isMobileExists(account.getMobile())) {
                    return Result.error("手机号已被使用");
                }
            }

            // 更新账号
            boolean success = updateById(account);
            if (success) {
                return Result.success(null);
            } else {
                return Result.error("更新账号失败");
            }

        } catch (Exception e) {
            log.error("更新账号失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 修改密码
     *
     * @param accountId   账号ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 修改结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> changePassword(Integer accountId, String oldPassword, String newPassword) {
        try {
            // 查询账号
            Account account = getById(accountId);
            if (account == null || account.getIsDeleted() == 1) {
                return Result.error("账号不存在");
            }

            // 验证旧密码
            if (!PasswordUtil.matches(oldPassword, account.getPassword())) {
                return Result.error("原密码错误");
            }

            // 验证新密码格式
            // if (newPassword == null || newPassword.length() < 6 || newPassword.length() > 12) {
            //     return Result.error("新密码长度必须在6-12位之间");
            // }

            // 更新密码
            account.setPassword(PasswordUtil.encode(newPassword));
            boolean success = updateById(account);

            if (success) {
                return Result.success(null);
            } else {
                return Result.error("修改密码失败");
            }

        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 锁定/解锁账号
     *
     * @param accountId 账号ID
     * @param flag      锁定标志：0启用 1禁用
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> lockAccount(Integer accountId, Integer flag) {
        try {
            if (flag == null || (flag != 0 && flag != 1)) {
                return Result.error("锁定标志参数错误");
            }

            Account account = getById(accountId);
            if (account == null || account.getIsDeleted() == 1) {
                return Result.error("账号不存在");
            }

            account.setIfEnable(flag);
            boolean success = updateById(account);

            if (success) {
                return Result.success(null);
            } else {
                return Result.error("操作失败");
            }

        } catch (Exception e) {
            log.error("锁定/解锁账号失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 删除账号
     *
     * @param accountId 账号ID
     * @return 删除结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteAccount(Integer accountId) {
        try {
            Account account = getById(accountId);
            if (account == null || account.getIsDeleted() == 1) {
                return Result.error("账号不存在");
            }

            // 软删除
            boolean success = removeById(accountId);

            if (success) {
                return Result.success(null);
            } else {
                return Result.error("删除账号失败");
            }

        } catch (Exception e) {
            log.error("删除账号失败", e);
            return Result.error("系统错误");
        }
    }

    /**
     * 分页查询账号列表
     *
     * @param pageRequest 分页请求
     * @param citycode    城市码（权限过滤）
     * @return 查询结果
     */
    public Result<MyPage<Account>> getAccountList(PageRequest<Account> pageRequest, String citycode) {
        try {
            Page<Account> page = pageRequest.toPage();

            LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Account::getIsDeleted, 0);

            // 城市码权限过滤
            if (StringUtils.hasText(citycode)) {
                wrapper.like(Account::getCitycode, citycode);
            }

            // 关键字搜索
            if (StringUtils.hasText(pageRequest.getKeyword())) {
                wrapper.and(w -> w.like(Account::getAccount, pageRequest.getKeyword())
                        .or().like(Account::getUsername, pageRequest.getKeyword())
                        .or().like(Account::getMobile, pageRequest.getKeyword()));
            }
            wrapper.ne(Account::getRole, 5);
            wrapper.orderByDesc(Account::getId);

            Page<Account> result = page(page, wrapper);
            MyPage<Account> myPage = MyPage.fromMybatisPlusPage(result);
            return Result.success(myPage);

        } catch (Exception e) {
            log.error("查询账号列表失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 获取账号详情
     *
     * @param accountId 账号ID
     * @return 账号详情
     */
    public Result<Account> getAccountInfo(Integer accountId) {
        try {
            Account account = getById(accountId);
            if (account == null || account.getIsDeleted() == 1) {
                return Result.error("账号不存在");
            }

            // 隐藏密码字段
            account.setPassword(null);

            return Result.success(account);

        } catch (Exception e) {
            log.error("获取账号详情失败", e);
            return Result.error("查询失败");
        }
    }

    // ========== 私有方法 ==========

    /**
     * 验证创建请求
     */
    private void validateCreateRequest(AccountCreateRequest request) throws BusinessException {
        // 检查手机号是否已存在
        if (isMobileExists(request.getMobile())) {
            throw new BusinessException(ResultEnum.MOBILE_EXISTS);
        }
    }

    /**
     * 检查手机号是否存在
     */
    private boolean isMobileExists(String mobile) {
        if (!StringUtils.hasText(mobile)) {
            return false;
        }
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getMobile, mobile)
                .eq(Account::getIsDeleted, 0);
        return count(wrapper) > 0;
    }
}